<?php
    /**
    * 
    */
    class BaseModel
    {   
        public $db = '';
        public $sql = '';
        public $data_key = '';
        public $data_value = '';
        public $database = '';
        public $prefix = '';
        public $order = 'desc';
        public $order_by = '';
        public $where = '';
        public $select = '*';

        function __construct()
        {
            $DB_CONFIG = array(
                'db_host' => '127.0.0.1',
                'db_port' => 3306,
                'db_user'  => 'root',
                'db_passwrod' => 'hackerliu',
                'db_engine' => 'mysql',
                'db_select' => 'lottery',
            );

            $dsn = 'mysql:host='.$DB_CONFIG['db_host'].';dbname='.$DB_CONFIG['db_select'].';';
            $this->db = new PDO($dsn,$DB_CONFIG['db_user'],$DB_CONFIG['db_passwrod']);
            $this->database = $DB_CONFIG['db_select'].'.';
        }

        function data($data){
            foreach ($data as $key => $value) {
                $this->data_key .= "`".$key."`,";
                $this->data_value .= "'".$value."',";
            }

            $this->data_key = trim($this->data_key,',');
            $this->data_value = trim($this->data_value,',');

            return $this;
        }

        function select($select){
            $this->select = $select;

            return $this;
        }

        function where($where){
            foreach ($where as $key => $value) {
                $this->where .= " ".$key."='".$value."' and";
            }
            $this->where = trim($this->where,'and');
            return $this;
        }

        function get_row($table){
            $table = $this->add_prefix($table);
            $sql = "SELECT {$this->select} FROM {$table} WHERE {$this->where}";
            $res = $this->db->query($sql);
            return array(
                    'rowCount' => $res->rowCount(),
                    'data'  => $res->fetch(PDO::FETCH_ASSOC),
                );
        }

        function get_all($table){
            $table = $this->add_prefix($table);
            $sql = "SELECT {$this->select} FROM {$table} WHERE {$this->where}";
            $res = $this->db->query($sql);
            return array(
                    'rowCount' => $res->rowCount(),
                    'data'  => $res->fetchAll(PDO::FETCH_ASSOC),
                );
        }


        function insert($table){
            $table = $this->add_prefix($table);
            $sql = "INSERT INTO {$table} ({$this->data_key}) VALUES ({$this->data_value});";
            $res = $this->db->query($sql);
            return (int)($res->errorCode());
        }


        /*添加表前缀*/
        function add_prefix($table){
            return $this->database.$this->prefix.$table;
        }

    }
?>